package com.easytouch.vmhdl.activity;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.easytouch.core.Configure;
import com.easytouch.core.DriverThread;
import com.easytouch.core.listener.OnDoorStateChangedListener;
import com.easytouch.core.listener.OnGoodsSelectedListener;
import com.easytouch.core.model.GoodsModel;
import com.easytouch.core.task.PickCodeCheckTask;
import com.easytouch.core.task.PickCodeReleaseTask;
import com.easytouch.core.task.TaskThreadPool;
import com.easytouch.core.utils.Log;
import com.easytouch.vmhdl.R;
import com.easytouch.vmhdl.fragment.BaseFragment;
import com.easytouch.vmhdl.fragment.GoodsFragment;
import com.easytouch.vmhdl.fragment.HomeFragment;
import com.easytouch.vmhdl.fragment.ListFragment;
import com.easytouch.vmhdl.fragment.PayFragment;
import com.easytouch.vmhdl.interfaces.ClickSwitchListener;
import com.easytouch.vmhdl.view.BitmapTouchChecker;
import com.easytouch.vmhdl.view.MainButton;

import java.lang.ref.SoftReference;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Pattern;

public class MainActivity extends FragmentActivity implements OnGoodsSelectedListener,OnDoorStateChangedListener,View.OnClickListener, ClickSwitchListener {

    public static final int FRAGMENT_HOME = 0;
    public static final int FRAGMENT_GOODS = 1;
    public static final int FRAGMENT_LIST = 2;
    public static final int FRAGMENT_PAY = 3;

    private TelephonyManager mTelephonyManager;
    private FragmentManager mFragmentManager;

    private RelativeLayout mRlTop;
    private TextView mTvMac;
    private TextView mTvPhone;
    private TextView mTvTime;
    private TextView mTvDate;
    private ImageView mIvSignal;

    private RelativeLayout mRlBottom;
    private Button mBtBack;
    private Button mBtPick;
    private MainButton mIvMenu;
    private LinearLayout mLlPick;
    private TextView mTvPickCode;

    private BaseFragment mFragment;

    private MyHandler mHandler;

    IntentReceiver mReceiver;
    IntentFilter mFilter;
    private ProgressDialog mProgressDialog;

    private Log mLogger = new Log("MainActivity.txt");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mRlTop = findViewById(R.id.rl_top);
        mTvMac = findViewById(R.id.tv_machine_code);
        mTvPhone = findViewById(R.id.tv_phone);
        mTvTime = findViewById(R.id.tv_time);
        mTvDate = findViewById(R.id.tv_date);
        mIvSignal = findViewById(R.id.iv_signal);

        mRlBottom = findViewById(R.id.rl_bottom);
        mBtBack = findViewById(R.id.bt_back);
        mBtBack.setOnClickListener(this);
        mBtPick = findViewById(R.id.bt_pickup);
        mBtPick.setOnClickListener(this);
        mIvMenu = findViewById(R.id.iv_menu);

        mLlPick = findViewById(R.id.ll_pick);
        mTvPickCode = findViewById(R.id.tv_pick_code);
        Button n0 = findViewById(R.id.bt_pick_n0);
        n0.setOnClickListener(this);
        Button n1 = findViewById(R.id.bt_pick_n1);
        n1.setOnClickListener(this);
        Button n2 = findViewById(R.id.bt_pick_n2);
        n2.setOnClickListener(this);
        Button n3 = findViewById(R.id.bt_pick_n3);
        n3.setOnClickListener(this);
        Button n4 = findViewById(R.id.bt_pick_n4);
        n4.setOnClickListener(this);
        Button n5 = findViewById(R.id.bt_pick_n5);
        n5.setOnClickListener(this);
        Button n6 = findViewById(R.id.bt_pick_n6);
        n6.setOnClickListener(this);
        Button n7 = findViewById(R.id.bt_pick_n7);
        n7.setOnClickListener(this);
        Button n8 = findViewById(R.id.bt_pick_n8);
        n8.setOnClickListener(this);
        Button n9 = findViewById(R.id.bt_pick_n9);
        n9.setOnClickListener(this);
        Button star = findViewById(R.id.bt_pick_xing);
        star.setOnClickListener(this);
        Button sharp = findViewById(R.id.bt_pick_jing);
        sharp.setOnClickListener(this);
        Button delete = findViewById(R.id.bt_pick_delete);
        delete.setOnClickListener(this);
        Button clear = findViewById(R.id.bt_pick_clear);
        clear.setOnClickListener(this);
        Button confirm = findViewById(R.id.bt_pick_confirm);
        confirm.setOnClickListener(this);
        Button back = findViewById(R.id.bt_pick_back);
        back.setOnClickListener(this);

        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeResource(getResources(),
                    R.drawable.goodslist_circle_mask);
        } catch (OutOfMemoryError e) {
            e.printStackTrace();
        }
        BitmapTouchChecker btc = new BitmapTouchChecker(bitmap);
        btc.setListener(this);
        mIvMenu.setTouchChecker(btc);

        mFragmentManager = getSupportFragmentManager();
        HomeFragment fragment = new HomeFragment();
        mFragmentManager.beginTransaction().replace(R.id.fl_content, fragment).commit();

        mTelephonyManager = (TelephonyManager) MainActivity.this.getSystemService(Context.TELEPHONY_SERVICE);
        if(mTelephonyManager != null) {
            mTelephonyManager.listen(new MyPhoneStateListener(), PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
        }
        DriverThread.getInstance().setOnGoodsSelectedListener(this);
        DriverThread.getInstance().setOnDoorStateChangedListener(this);

        mHandler = new MyHandler(this);
        mHandler.sendEmptyMessage(0);

        mFilter = new IntentFilter();
        mReceiver = new IntentReceiver();
        mFilter.addAction(PickCodeCheckTask.INTENT_PICK_RESULT);
        registerReceiver(mReceiver, mFilter);
    }

    public void goFragment(final int toFragment, final Bundle bundle)
    {
        BaseFragment fragment;
        switch (toFragment)
        {
            case FRAGMENT_HOME:
                fragment = new HomeFragment();
                break;
            case FRAGMENT_GOODS:
                fragment = new GoodsFragment();
                break;
            case FRAGMENT_LIST:
                fragment = new ListFragment();
                break;
            case FRAGMENT_PAY:
                fragment = new PayFragment();
                break;
            default:
                return;
        }
        if(fragment != null)
        {
            mFragment = fragment;
        }
        else
        {
            mFragment = null;
            return;
        }
        FragmentTransaction ft = mFragmentManager.beginTransaction();
        if(bundle != null)
        {
            fragment.setArguments(bundle);
        }
        ft.replace(R.id.fl_content, fragment);
        ft.commitAllowingStateLoss();
    }

    private void updateTop()
    {
        String macString = getString(R.string.main_mac);
        mTvMac.setText(String.format(macString, Configure.getMacNo()));
        String phoneString = getString(R.string.main_phone);
        mTvPhone.setText(String.format(phoneString, Configure.getCustomConfigData("config.ini", "phone")));
        SimpleDateFormat formatTime = new SimpleDateFormat("HH:mm", Locale.US);
        mTvTime.setText(formatTime.format(new Date()));
        SimpleDateFormat formatDate = new SimpleDateFormat("yyyy/MM/dd",Locale.US);
        mTvDate.setText(formatDate.format(new Date()));
    }

    public void hideTop()
    {
        mRlTop.setVisibility(View.GONE);
    }

    public void showTop()
    {
        mRlTop.setVisibility(View.VISIBLE);
    }

    public void hideBottom()
    {
        mRlBottom.setVisibility(View.GONE);
    }

    public void showBottom(final boolean isShowMenu, final boolean isShowPick)
    {
        if(isShowMenu)
        {
            mIvMenu.setBackgroundResource(R.drawable.goodslist_circle);
            mIvMenu.setVisibility(View.VISIBLE);
        }
        else
        {
            mIvMenu.setVisibility(View.INVISIBLE);
        }
        if(isShowPick)
        {
            mBtPick.setVisibility(View.VISIBLE);
        }
        else
        {
            mBtPick.setVisibility(View.GONE);
        }
        mRlBottom.setVisibility(View.VISIBLE);
    }

    private void cleanUp()
    {
        DriverThread.getInstance().removeOnGoodsSelectedListener();
        DriverThread.getInstance().removeOnDoorStateChangedListener();
        unregisterReceiver(mReceiver);
    }

    private void addChar(final String pChar)
    {
        String content = mTvPickCode.getText().toString();
        if(Pattern.matches("[0-9]*", content))
        {
            if(content.length() > 12)
            {
                return;
            }
            content += pChar;
            mTvPickCode.setText(content);
        }
        else
        {
            mTvPickCode.setText(pChar);
        }
    }

    private void deleteChar()
    {
        String content = mTvPickCode.getText().toString();
        if(content == null || "".equals(content))
        {
            return;
        }
        if(Pattern.matches("[0-9]*", content))
        {
            content = content.substring(0, content.length() - 1);
            mTvPickCode.setText(content);
        }
        else
        {
            mTvPickCode.setText("");
        }
    }

    public void showPick()
    {
        mLlPick.setVisibility(View.VISIBLE);
    }

    private void doPick()
    {
        String content = mTvPickCode.getText().toString();
        if(mProgressDialog == null)
        {
            mProgressDialog = new ProgressDialog(this);
        }
        if(mProgressDialog.isShowing())
            return;
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        mProgressDialog.setCancelable(false);
        mProgressDialog.setMessage(getResources().getString(R.string.loading));
        mProgressDialog.show();
        //提货码
        TaskThreadPool.addTaskAndRun(new PickCodeCheckTask(content));
    }

    @Override
    public void onBackPressed() {
        return;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onGoodsSelected(int box, int column, int goodsId, int price) {
        mLogger.i("selected goods, box:" + String.valueOf(box) + " column:" + String.valueOf(column));
        final String goodsJson = DriverThread.getInstance().getGoodsInfo(box, column);
        if(goodsJson == null)
        {
            mLogger.e("no goods");
            return;
        }
        if(!GoodsModel.isGoodsHaveStock(goodsJson))
        {
            mLogger.e("no stock");
            return;
        }
        this.runOnUiThread(() -> {
            Bundle bundle = new Bundle();
            bundle.putString(PayFragment.PARAM_GOODS, goodsJson);
            bundle.putBoolean(PayFragment.PARAM_IS_SELECT, true);
            goFragment(MainActivity.FRAGMENT_PAY, bundle);
        });
    }

    @Override
    public void onDoorStateChanged(boolean isDoorOpen) {
        if(isDoorOpen)
        {
            runOnUiThread(() -> {
                mLogger.i("door open");
                cleanUp();
                Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                startActivity(intent);
                MainActivity.this.finish();
            });
        }
        else
        {
            mLogger.i("door close");
        }
    }

    @Override
    public void onClickSwitchListener(final int type) {
        if (type == 1)
        {
            //冷饮
            mIvMenu.setBackgroundResource(R.drawable.goodslist_circle_cool);
            if(mFragment != null)
            {
                mFragment.onMenuPressed(BaseFragment.MENU_COOL);
            }
        }
        else if(type == 2)
        {
            //全部
            mIvMenu.setBackgroundResource(R.drawable.goodslist_circle);
            if(mFragment != null)
            {
                mFragment.onMenuPressed(BaseFragment.MENU_ALL);
            }
        }
        else if(type == 3)
        {
            //热饮
            mIvMenu.setBackgroundResource(R.drawable.goodslist_circle_hot);
            if(mFragment != null)
            {
                mFragment.onMenuPressed(BaseFragment.MENU_HOT);
            }
        }
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id)
        {
            case R.id.bt_back:
                if(mFragment != null)
                {
                    mFragment.onBackButtonPressed();
                }
                break;
            case R.id.bt_pickup:
                showPick();
                break;
            case R.id.bt_pick_back:
                mLlPick.setVisibility(View.GONE);
                break;
            case R.id.bt_pick_n0:
                addChar("0");
                break;
            case R.id.bt_pick_n1:
                addChar("1");
                break;
            case R.id.bt_pick_n2:
                addChar("2");
                break;
            case R.id.bt_pick_n3:
                addChar("3");
                break;
            case R.id.bt_pick_n4:
                addChar("4");
                break;
            case R.id.bt_pick_n5:
                addChar("5");
                break;
            case R.id.bt_pick_n6:
                addChar("6");
                break;
            case R.id.bt_pick_n7:
                addChar("7");
                break;
            case R.id.bt_pick_n8:
                addChar("8");
                break;
            case R.id.bt_pick_n9:
                addChar("9");
                break;
            case R.id.bt_pick_xing:
                addChar("*");
                break;
            case R.id.bt_pick_jing:
                addChar("#");
                break;
            case R.id.bt_pick_clear:
                mTvPickCode.setText("");
                break;
            case R.id.bt_pick_delete:
                deleteChar();
                break;
            case R.id.bt_pick_confirm:
                doPick();
                break;
        }
    }

    class MyPhoneStateListener extends PhoneStateListener {

        @Override
        public void onSignalStrengthsChanged(SignalStrength signalStrength) {
            super.onSignalStrengthsChanged(signalStrength);
            int asu = signalStrength.getGsmSignalStrength();
            if(asu <= 2)
            {
                //no signal
                mIvSignal.setImageResource(R.drawable.signal_0);
            }
            else if(asu < 4)
            {
                //weak
                mIvSignal.setImageResource(R.drawable.signal_1);
            }
            else if(asu < 7)
            {
                //mid
                mIvSignal.setImageResource(R.drawable.signal_2);
            }
            else if(asu < 10)
            {
                //strong
                mIvSignal.setImageResource(R.drawable.signal_3);
            }
            else if(asu < 12)
            {
                //strong
                mIvSignal.setImageResource(R.drawable.signal_4);
            }
            else
            {
                //full signal
                mIvSignal.setImageResource(R.drawable.signal_5);
            }
        }
    }

    class MyHandler extends Handler
    {

        private SoftReference<MainActivity> mActivity;

        public MyHandler(MainActivity activity)
        {
            mActivity = new SoftReference<MainActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg)
        {
            super.handleMessage(msg);
            switch (msg.what)
            {
                case 0: //定时器
                {
                    mActivity.get().updateTop();
                    break;
                }
            }
        }
    }

    class IntentReceiver extends BroadcastReceiver
    {
        @Override
        public void onReceive(Context context, Intent intent)
        {
            String action = intent.getAction();
            if(action.equals(PickCodeCheckTask.INTENT_PICK_RESULT)) //提货码结果
            {
                mLogger.i("INTENT_PICK_RESULT");
                if(mProgressDialog != null)
                {
                    mProgressDialog.dismiss();
                }
                int result = intent.getIntExtra(PickCodeCheckTask.EXTRA_PICK_RESULT_CODE, -1);
                String message = intent.getStringExtra(PickCodeCheckTask.EXTRA_PICK_RESULT_MESSAGE);
                String code = intent.getStringExtra(PickCodeCheckTask.EXTRA_PICK_CODE);
                mLogger.i("INTENT_PICK_RESULT message:" + message);
                switch (result)
                {
                    case 1:
                        mLogger.i("INTENT_PICK_RESULT case 1");
                        if(message == null || message.equals(""))
                        {
                            mTvPickCode.setText(R.string.pick_no_goods);
                            TaskThreadPool.addTaskAndRun(new PickCodeReleaseTask(code, true));
                            break;
                        }
                        String[] idArray = message.split("-");
                        if(idArray == null || idArray.length < 1)
                        {
                            mTvPickCode.setText(R.string.pick_no_goods);
                            TaskThreadPool.addTaskAndRun(new PickCodeReleaseTask(code, true));
                            break;
                        }
                        String goodsCode = idArray[0];
                        String goodsJson = DriverThread.getInstance().getRoadInfo(goodsCode);
                        if(goodsJson == null)
                        {
                            mLogger.e("pick no goods");
                            mTvPickCode.setText(R.string.pick_no_goods);
                            TaskThreadPool.addTaskAndRun(new PickCodeReleaseTask(code, true));
                            break;
                        }
                        if(!GoodsModel.isGoodsHaveStock(goodsJson))
                        {
                            mLogger.e("pick no stock");
                            mTvPickCode.setText(R.string.pick_no_stock);
                            TaskThreadPool.addTaskAndRun(new PickCodeReleaseTask(code, true));
                            break;
                        }
                        mLlPick.setVisibility(View.GONE);
                        Bundle bundle = new Bundle();
                        bundle.putString(PayFragment.PARAM_GOODS, goodsJson);
                        bundle.putString(PayFragment.PARAM_CODE, code);
                        MainActivity.this.goFragment(MainActivity.FRAGMENT_PAY, bundle);
                        break;
                    case 2:
                        mTvPickCode.setText(R.string.pick_used);
                        break;
                    case 3:
                        mTvPickCode.setText(R.string.pick_not_exist);
                        break;
                    case 4:
                        mTvPickCode.setText(R.string.pick_expird);
                        break;
                    case 5:
                        mTvPickCode.setText(R.string.pick_locked);
                        break;
                    case -1:
                        mTvPickCode.setText(R.string.pick_local_data_error);
                        break;
                    case -2:
                        mTvPickCode.setText(R.string.pick_net_error);
                        break;
                    case -3:
                        mTvPickCode.setText(R.string.pick_data_error);
                        break;
                    default:
                        break;
                }
            }
        }
    }
}
